﻿var approvalPageVue = new Vue({
    el: "#approvalPage",
    data: {
        record: {                       //保养记录格式
            BaseInfo: {},
            Equipment: {
                BaseInfo: {},
                MaintainInfo: {}
            },
            TemplateForm: {
                BaseInfo: {},
                Items: []
            },
            ItemRecords: [],
            CheckerInfo: {},
            ApproverInfo: {},
            Approvals: []
        },
        templateFormList: [],           //保养单模板列表
        statusDictionary: {},           //设备状态字典
        sectionStatusDictionary: []     //签核节点状态字典
    },
    methods: {
        ApproveRecord: function (event, approvalSection, sectionStatus) {
            event.preventDefault();
            ApproveMaintainRecord(this, approvalSection, sectionStatus);
        }
    },
    created: function () {
        //页面加载前初始的数据
        InitialAztechScript();
    },
    mounted: function () {
        var vue = this;
        //页面加载后初始的数据
        var recordID = GetQueryString("RecordID");

        vue.statusDictionary = GlobalDictionary.GetEquipmentStatusDictionary();
        vue.sectionStatusDictionary = GlobalDictionary.GetApprovalSectionStatusDictionary();
        GetMaintainRecordByID(vue, recordID);

        //设置保养日期时间选择器
        $("#recordDatePicker").datetimepicker({
            format: "yyyy-MM-dd",
            autoclose: true,
            minView: 2
        });
        //由于datetimepicker插件不能让Vue双向绑定数据生效，所以需监听事件赋值
        $("#recordDatePicker").datetimepicker().on("hide", function (event) {
            vue.record.BaseInfo.RecordDate = $(event.target).val();
            CheckRecordDate(vue);
        });
        
    }
});

/**
 * 设置保养日期
 */
function GetRecordDate(vue, targetDate) {
    vue.record.BaseInfo.RecordDate = targetDate;
}

/**
 * 根据ID查询保养记录
 */
function GetMaintainRecordByID(vue, recordID) {
    if (recordID != null && recordID > 0) {
        ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Maintain/GetApprovalMaintainRecordByID?RecordID=" + recordID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    console.log(JSON.stringify(res.data));
                    vue.record = res.data;
                    vue.record.BaseInfo.RecordDate = CSharpToJsDate(vue.record.BaseInfo.RecordDate)

                    vue.$nextTick(function () {
                        //获取该设备所有保养单模板
                        GetTemplateFormListByEquipmentTypeID(vue, vue.record.Equipment.BaseInfo.TypeID);
                        //设置所有保养项目状态
                        for (var idx in vue.record.ItemRecords) {
                            ItemRecordCheck(vue, idx, vue.record.ItemRecords[idx].IsOk);
                            ItemRecordRemark(vue, idx, vue.record.ItemRecords[idx].Remark);
                        }
                    });

                    //检查签核节点信息并转换
                    for (var idx in vue.record.Approvals) {
                        var appr = vue.record.Approvals[idx];
                        //转换C#签核时间
                        appr.SectionDetail.UpdateDate = CSharpToJsDate(appr.SectionDetail.UpdateDate);
                        //如果不存在签核人，则检查当前用户是拥有签核权限组，如果是则设置为当前签核人
                        if (!appr.SectionApprover) {
                            var approverGroupID = appr.SectionDetail.ApproverGroupID;
                            var lastAppr = vue.record.Approvals[idx - 1];
                            //判断是否有上一签核
                            if (!lastAppr || lastAppr.SectionDetail.SectionStatus == "1") {
                                if (GlobalUser.hasGroup(approverGroupID)) {
                                    appr.SectionApprover = GlobalUser.getUserInfo();
                                    appr.SectionDetail.ApproverID = GlobalUser.getUserInfo().ID;
                                }
                            }
                        }
                    }
                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            },
            complete: function () {
                HideAzLoading();
            }
        })
    }
}

/**
 * 签核保养记录
 */
function ApproveMaintainRecord(vue, approvalSection, sectionStatus) {
    if (confirm("确认签核保养记录Confirm and sign off maintenance records？")) {
        ShowAzLoading();
        $.ajax({
            type: "POST",
            url: "/Maintain/ApproveMaintainRecord",
            data: {
                ApproverID: approvalSection.ApproverID,
                Remark: approvalSection.Remark,
                RecordID: approvalSection.RecordID,
                SectionID: approvalSection.ID,
                SectionStatus: sectionStatus
            },
            success: function (res) {
                if (res.status == "Success") {
                    toastr.success("签核保养记录成功The maintenance record is signed successfully。");
                    //GetMaintainRecordByID(vue, approvalSection.RecordID);
                    $.ajax({
                        type: "GET",
                        url: "/Maintain/ListApprovalMaintainRecords?v=" + Math.random(),
                        success: function (res) {
                            if (res.status == "Success") {
                                vue.approvalMaintainRecordList = res.data;
                                if (vue.approvalMaintainRecordList.length > 0) {
                                    var record_ID = vue.approvalMaintainRecordList[0].BaseInfo.ID;
                                    var url = "/Home/Approval?RecordID=" + record_ID;
                                    window.location.href = url;
                                }
                                else {
                                    GetMaintainRecordByID(vue, approvalSection.RecordID);
                                }
                            } else {
                                GetMaintainRecordByID(vue, approvalSection.RecordID);
                                toastr.error(res.message);
                            }
                        },
                        error: function (err) {
                            GetMaintainRecordByID(vue, approvalSection.RecordID);
                            console.log(err);
                            toastr.error("获取下一笔保养记录失败，请稍候再试Failed to get the next maintenance record. Please try again later。");
                        }
                    });




                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            },
            complete: function () {
                HideAzLoading();
                $("button").removeAttr("disabled");
            }
        })
    }
}

/**
 * 根据设备类型ID获取该类型的所有保养单模板
 */
function GetTemplateFormListByEquipmentTypeID(vue, equipmentTypeID) {
    ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Maintain/ListTemplateFormByEquipmentTypeID?IsDisable=false&TypeID=" + equipmentTypeID + "&v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                //设置对应设备可选保养单模板
                vue.templateFormList = res.data;

                //如果是新纪录则默认第一保养单模板
                if (vue.isNewRecord) {
                    vue.$nextTick(function () {
                        if (vue.templateFormList.length > 0) {
                            vue.record.TemplateForm.BaseInfo.ID = vue.templateFormList[0].ID;
                            //获得第一保养单模板对应保养项目
                            GetTemplateFormByID(vue, vue.record.TemplateForm.BaseInfo.ID);
                        }
                    });
                }
            } else {
                toastr.error(res.message);
            }
            HideAzLoading();
        },
        error: function (err) {
            HideAzLoading();
            console.log(err);
            toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
        }
    });
}


/**
 * 根据ID查询保养单模板详细（包含对应保养项目）
 */
function GetTemplateFormByID(vue, formID) {
    if (formID != null && formID > 0) {
        ShowAzLoading();
        $.ajax({
            type: "GET",
            url: "/Maintain/GetTemplateFormByID?FormID=" + formID + "&v=" + Math.random(),
            success: function (res) {
                if (res.status == "Success") {
                    vue.record.TemplateForm = res.data;
                    vue.record.BaseInfo.FormID = vue.record.TemplateForm.BaseInfo.ID;

                    //初始保养记录的ItemRecords
                    //重置项目输入框初始状态
                    vue.$nextTick(function () {
                        $("li input").each(function () {
                            $(this).hide();
                        });
                        ResetItemRecords(vue);
                        ResizeAzModal();
                    });
                } else {
                    toastr.error(res.message);
                }
                HideAzLoading();
            },
            error: function (err) {
                HideAzLoading();
                console.log(err);
                toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
            }
        });
    }
}

/**
 * 初始保养记录中保养项目记录列表
 */
function ResetItemRecords(vue) {
    vue.record.ItemRecords = [];
    for (var idx in vue.record.TemplateForm.Items) {
        var record = {
            ItemID: vue.record.TemplateForm.Items[idx].ID,
            IsOk: -1,
            Remark: ""
        }
        vue.record.ItemRecords.push(record);
    }
}

/**
 * 设置保养项目记录操作结果
 */
function ItemRecordCheck(vue, index, isPass) {
    var liTag = "#itemRecord" + index;
    var inputTag = "#itemRemark" + index;

    vue.record.ItemRecords[index].IsOk = isPass;
    if (isPass == true) {
        vue.record.ItemRecords[index].Remark = "";
        $(liTag).addClass("list-group-item-success");
        $(liTag).removeClass("list-group-item-danger");
        $(inputTag).val("");
        $(inputTag).slideUp();
    } else {
        $(liTag).removeClass("list-group-item-success");
        $(liTag).addClass("list-group-item-danger");
        $(inputTag).slideDown();
    }
    ResizeAzModal();
}

/**
 * 保养项目不通过时，记录处理方法及结果。
 */
function ItemRecordRemark(vue, index, remark) {
    var inputTag = "#itemRemark" + index;
    vue.record.ItemRecords[index].Remark = remark;
    $(inputTag).val(remark);
}

/**
 * 清空信息
 */
function ResetForm(vue) {
    vue.record = {
        BaseInfo: {},
        Equipment: {
            BaseInfo: {},
            MaintainInfo: {}
        },
        TemplateForm: {
            BaseInfo: {},
            Items: []
        },
        ItemRecords: [],
        CheckerInfo: {},
        ApproverInfo: {}
    };
    vue.templateFormList = [];
    vue.$nextTick(function () {
        ResizeAzModal();
    });
}



